#include "waveshare_lcd_146_board.h"
#include "otto_emoji_display.h"

LV_FONT_DECLARE(font_puhui_16_4);
LV_FONT_DECLARE(font_awesome_16_4);

#define TAG "waveshare_lcd_1_46"

uint8_t button_state = 0;   // 按钮状态

// CustomLcdDisplay成员函数实现
void CustomLcdDisplay::rounder_event_cb(lv_event_t * e) {
    lv_area_t * area = (lv_area_t *)lv_event_get_param(e);
    uint16_t x1 = area->x1;
    uint16_t x2 = area->x2;

    area->x1 = (x1 >> 2) << 2;
    area->x2 = ((x2 >> 2) << 2) + 3;
}

CustomLcdDisplay::CustomLcdDisplay(esp_lcd_panel_io_handle_t io_handle, 
                esp_lcd_panel_handle_t panel_handle,
                int width,
                int height,
                int offset_x,
                int offset_y,
                bool mirror_x,
                bool mirror_y,
                bool swap_xy) 
    : SpiLcdDisplay(io_handle, panel_handle,
                width, height, offset_x, offset_y, mirror_x, mirror_y, swap_xy,
                {
                    .text_font = &font_puhui_16_4,
                    .icon_font = &font_awesome_16_4,
                    .emoji_font = font_emoji_64_init(),
                }) {
    DisplayLockGuard lock(this);
    lv_display_add_event_cb(display_, rounder_event_cb, LV_EVENT_INVALIDATE_AREA, NULL);
}

// CustomBoard静态成员初始化
CustomBoard* CustomBoard::instance_ = nullptr;

// CustomBoard成员函数实现
void CustomBoard::InitializeI2c() {
    i2c_master_bus_config_t i2c_bus_cfg = {
        .i2c_port = (i2c_port_t)0,
        .sda_io_num = I2C_SDA_IO,
        .scl_io_num = I2C_SCL_IO,
        .clk_source = I2C_CLK_SRC_DEFAULT,
    };
    ESP_ERROR_CHECK(i2c_new_master_bus(&i2c_bus_cfg, &i2c_bus_));
}

void CustomBoard::InitializeTca9554() {
    esp_err_t ret = esp_io_expander_new_i2c_tca9554(i2c_bus_, I2C_ADDRESS, &io_expander);
    if(ret != ESP_OK) {
        ESP_LOGE(TAG, "TCA9554 create returned error");
    }

    ret = esp_io_expander_set_dir(io_expander, IO_EXPANDER_PIN_NUM_0 | IO_EXPANDER_PIN_NUM_1, IO_EXPANDER_OUTPUT);
    ESP_ERROR_CHECK(ret);
    ret = esp_io_expander_set_level(io_expander, IO_EXPANDER_PIN_NUM_0 | IO_EXPANDER_PIN_NUM_1, 1);
    ESP_ERROR_CHECK(ret);
    vTaskDelay(pdMS_TO_TICKS(300));
    ret = esp_io_expander_set_level(io_expander, IO_EXPANDER_PIN_NUM_0 | IO_EXPANDER_PIN_NUM_1, 0);
    ESP_ERROR_CHECK(ret);
    vTaskDelay(pdMS_TO_TICKS(300));
    ret = esp_io_expander_set_level(io_expander, IO_EXPANDER_PIN_NUM_0 | IO_EXPANDER_PIN_NUM_1, 1);
    ESP_ERROR_CHECK(ret);
}

void CustomBoard::InitializeSpi() {
    ESP_LOGI(TAG, "Initialize QSPI bus");
    const spi_bus_config_t bus_config = TAIJIPI_SPD2010_PANEL_BUS_QSPI_CONFIG(
        QSPI_PIN_NUM_LCD_PCLK,
        QSPI_PIN_NUM_LCD_DATA0,
        QSPI_PIN_NUM_LCD_DATA1,
        QSPI_PIN_NUM_LCD_DATA2,
        QSPI_PIN_NUM_LCD_DATA3,
        QSPI_LCD_H_RES * 80 * sizeof(uint16_t));
    ESP_ERROR_CHECK(spi_bus_initialize(QSPI_LCD_HOST, &bus_config, SPI_DMA_CH_AUTO));
}

void CustomBoard::InitializeSpd2010Display() {
    esp_lcd_panel_io_handle_t panel_io = nullptr;
    esp_lcd_panel_handle_t panel = nullptr;

    ESP_LOGI(TAG, "Install panel IO");
    const esp_lcd_panel_io_spi_config_t io_config = SPD2010_PANEL_IO_QSPI_CONFIG(QSPI_PIN_NUM_LCD_CS, NULL, NULL);
    ESP_ERROR_CHECK(esp_lcd_new_panel_io_spi((esp_lcd_spi_bus_handle_t)QSPI_LCD_HOST, &io_config, &panel_io));

    ESP_LOGI(TAG, "Install SPD2010 panel driver");
    spd2010_vendor_config_t vendor_config = {
        .flags = {
            .use_qspi_interface = 1,
        },
    };
    const esp_lcd_panel_dev_config_t panel_config = {
        .reset_gpio_num = QSPI_PIN_NUM_LCD_RST,
        .rgb_ele_order = LCD_RGB_ELEMENT_ORDER_RGB,
        .bits_per_pixel = QSPI_LCD_BIT_PER_PIXEL,
        .vendor_config = &vendor_config,
    };
    ESP_ERROR_CHECK(esp_lcd_new_panel_spd2010(panel_io, &panel_config, &panel));

    esp_lcd_panel_reset(panel);
    esp_lcd_panel_init(panel);
    esp_lcd_panel_disp_on_off(panel, true);
    esp_lcd_panel_swap_xy(panel, DISPLAY_SWAP_XY);
    esp_lcd_panel_mirror(panel, DISPLAY_MIRROR_X, DISPLAY_MIRROR_Y);
    this->display_ = new OttoEmojiDisplay(
            panel_io, panel, DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_OFFSET_X, DISPLAY_OFFSET_Y,
            DISPLAY_MIRROR_X, DISPLAY_MIRROR_Y, DISPLAY_SWAP_XY,
            {
                .text_font = &font_puhui_16_4,
                .icon_font = &font_awesome_16_4,
                .emoji_font = DISPLAY_HEIGHT >= 240 ? font_emoji_64_init() : font_emoji_32_init(),
            });
}

void CustomBoard::InitializeButtonsCustom() {
    gpio_reset_pin(BOOT_BUTTON_GPIO);
    gpio_set_direction(BOOT_BUTTON_GPIO, GPIO_MODE_INPUT);
    gpio_reset_pin(PWR_BUTTON_GPIO);
    gpio_set_direction(PWR_BUTTON_GPIO, GPIO_MODE_INPUT);
    gpio_reset_pin(PWR_Control_PIN);
    gpio_set_direction(PWR_Control_PIN, GPIO_MODE_OUTPUT);
    gpio_set_level(PWR_Control_PIN, true);
}

void CustomBoard::InitializeButtons() {
    instance_ = this;
    InitializeButtonsCustom();

    button_config_t boot_btn_config = {
        .long_press_time = 2000,
        .short_press_time = 0
    };
    boot_btn_driver_ = (button_driver_t*)calloc(1, sizeof(button_driver_t));
    boot_btn_driver_->enable_power_save = false;
    boot_btn_driver_->get_key_level = [](button_driver_t *button_driver) -> uint8_t {
        return !gpio_get_level(BOOT_BUTTON_GPIO);
    };
    ESP_ERROR_CHECK(iot_button_create(&boot_btn_config, boot_btn_driver_, &boot_btn));
    iot_button_register_cb(boot_btn, BUTTON_SINGLE_CLICK, nullptr, [](void* button_handle, void* usr_data) {
        button_state = 1;
        ESP_LOGI(TAG, "Boot button single click detected");
    }, this);
    iot_button_register_cb(boot_btn, BUTTON_LONG_PRESS_START, nullptr, [](void* button_handle, void* usr_data) {
        button_state = 2;
        ESP_LOGI(TAG, "Boot button long press start detected");
    }, this);

    button_config_t pwr_btn_config = {
        .long_press_time = 5000,
        .short_press_time = 0
    };
    pwr_btn_driver_ = (button_driver_t*)calloc(1, sizeof(button_driver_t));
    pwr_btn_driver_->enable_power_save = false;
    pwr_btn_driver_->get_key_level = [](button_driver_t *button_driver) -> uint8_t {
        return !gpio_get_level(PWR_BUTTON_GPIO);
    };
    ESP_ERROR_CHECK(iot_button_create(&pwr_btn_config, pwr_btn_driver_, &pwr_btn));
    iot_button_register_cb(pwr_btn, BUTTON_SINGLE_CLICK, nullptr, [](void* button_handle, void* usr_data) {
        // 短按无处理
    }, this);
    iot_button_register_cb(pwr_btn, BUTTON_LONG_PRESS_START, nullptr, [](void* button_handle, void* usr_data) {
        auto self = static_cast<CustomBoard*>(usr_data);
        if(self->GetBacklight()->brightness() > 0) {
            self->GetBacklight()->SetBrightness(0);
            gpio_set_level(PWR_Control_PIN, false);
        } else {
            self->GetBacklight()->RestoreBrightness();
            gpio_set_level(PWR_Control_PIN, true);
        }
    }, this);
}

CustomBoard::CustomBoard() { 
    InitializeI2c();
    InitializeTca9554();
    InitializeSpi();
    InitializeSpd2010Display();
    InitializeButtons();
    GetBacklight()->RestoreBrightness();
}

CustomBoard& CustomBoard::GetInstance() {
    static CustomBoard* instance = static_cast<CustomBoard*>(create_board());
    return *instance;
}

Display* CustomBoard::GetDisplay() {
    return display_;
}

Backlight* CustomBoard::GetBacklight() {
    static PwmBacklight backlight(DISPLAY_BACKLIGHT_PIN, DISPLAY_BACKLIGHT_OUTPUT_INVERT);
    return &backlight;
}

DECLARE_BOARD(CustomBoard);
